<?php
/**
 * 系统设置
 * @since 1.0 <2015-5-26> SoChishun <14507247@qq.com> Added.
 */
include 'function.php';
$module_config = load_config();
if (!$module_config || !isset($module_config['db_object_dir'])) {
    die('资源文件目录不存在!');
}
$subdir = $module_config['db_object_dir'];
if ('create' == query('action')) {
    die(json_encode(create_table()));
}
?>
<!DOCTYPE html>
<html>
    <head>
        <title>系统设置-INSTALL</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <link href="//libs.useso.com/js/yui/3.17.2/cssreset/cssreset-min.css" rel="stylesheet" />
        <link href="./Skin/theme-blue.css" rel="stylesheet" />
        <script src="//libs.useso.com/js/jquery/1.11.1/jquery.min.js" type="text/javascript"></script>   
    </head>
    <body class="page-step-setting">
        <div class="header">
            <div class="frame-style">
                <div class="logo">INSTALL安装向导</div>
                <div class="breadcrumb">
                    <ul>
                        <li><a href="./install.php">欢迎界面</a></li>
                        <li><a href="./step_env.php">环境检测</a></li>
                        <li><a href="./step_setting.php">系统配置</a></li>
                        <li class="cur">初始化数据</li>
                        <li>完成安装</li>
                    </ul>
                </div>
            </div>
        </div>
        <div class="bodier">
            <form method="post" action="#" id="frmDb">
                <h3>数据库信息</h3>
                <table cellspacing="0" class="table-form">
                    <tr><th>数据库服务器</th><td><input type="text" name="db_host" placeholder="数据库服务器" required="required" value="localhost" /><em>(一般为localhost或ip地址)</em></td></tr>
                    <tr><th>数据库名</th><td><input type="text" name="db_name" placeholder="数据库名" required="required" value="db_xcall" title="dbxcrm_v1" /></td></tr>
                    <tr><th>数据库用户名</th><td><input type="text" name="db_user" placeholder="数据库用户名" required="required" value="xcall" /></td></tr>
                    <tr><th>数据库密码</th><td><input type="text" name="db_pwd" placeholder="数据库密码" required="required" value="root!@#xcall098)(*Admin%^&" /></td></tr>
                    <tr><th>数据表前缀</th><td><input type="text" name="db_prefix" placeholder="数据表前缀" value="" /></td></tr>
                </table>
                <div class="footer">
                    <span style="display:none"><input id="btn-submit" type="submit" value="提交" /></span>
                    <a href="#" onclick="return submit_form();">安装</a><a href="#" onclick="return reset_form()">重置</a>
                </div>
            </form>
            <fieldset style="display: none; margin-top:20px;">
                <legend>安装数据库</legend>
                <div style="max-height:420px; width:800px; overflow-y: auto;">
                    <table id="creating-tables-status" class="table-grid" cellspacing="0">
                        <tr><th>对象名称</th><th class="al-right">安装结果</th></tr>
                        <?php
                        $i = 1;
                        // 支持三级子目录遍历 2015-7-17 SoChishun Added.
                        foreach ($subdir as $dir) {
                            if (!file_exists($dir)) {
                                echo '<tr><td colspan="2">', $dir, ' 不存在!</td></tr>';
                                continue;
                            }
                            $odir = opendir($dir);
                            while (false !== ($file = readdir($odir))) {
                                if ('.' == $file || '..' == $file) {
                                    continue;
                                }
                                $filename = str_replace('//', '/', $dir . '/' . $file);
                                if (!is_dir($filename)) {
                                    if (strpos($file, '.sql')) {
                                        echo '<tr id="dbo_' . $i . '" title="' . $filename . '"><td class="table">' . $i . '.' . $file . '</td><td class="status break-line al-right"><span class="orange">待安装</span></td></tr>';
                                        $i++;
                                    }
                                    continue;
                                }
                                $odir2 = opendir($filename);
                                while (false !== ($file2 = readdir($odir2))) {
                                    if ('.' == $file2 || '..' == $file2) {
                                        continue;
                                    }
                                    $filename2 = str_replace('//', '/', $filename . '/' . $file2);
                                    if (!is_dir($filename2)) {
                                        if (strpos($file2, '.sql')) {
                                            echo '<tr id="dbo_' . $i . '" title="' . $filename2 . '"><td class="table">' . $i . '.' . $file2 . '</td><td class="status break-line al-right"><span class="orange">待安装</span></td></tr>';
                                            $i++;
                                        }
                                        continue;
                                    }
                                    $odir3 = opendir($filename2);
                                    while (false !== ($file3 = readdir($odir3))) {
                                        if ('.' == $file3 || '..' == $file3) {
                                            continue;
                                        }
                                        $filename3 = str_replace('//', '/', $filename2 . '/' . $file3);
                                        if (!is_dir($filename3)) {
                                            if (strpos($file3, '.sql')) {
                                                echo '<tr id="dbo_' . $i . '" title="' . $filename3 . '"><td class="table">' . $i . '.' . $file3 . '</td><td class="status break-line al-right"><span class="orange">待安装</span></td></tr>';
                                                $i++;
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        ?>
                    </table>
                </div>
                <div class="footer">
                    <a href="./step_env.php">上一步</a><a href="./step_data.php">下一步</a>
                </div>
            </fieldset>
        </div>
        <script type="text/javascript">
            // 2015-5-26 SoChishun Added.
            function submit_form() {
                document.getElementById('btn-submit').click();
                return false;
            }
            $('#frmDb').submit(function () {
                $(this).next().show();
                create_tables();
                return false;
            })
            function reset_form() {
                document.getElementById('frmDb').reset();
                return false;
            }
            function create_tables() {
                var params = $('#frmDb').serialize();
                var url = 'step_setting.php';
                $('#creating-tables-status tr[id]').each(function (i) {
                    var $tr = $(this);
                    var arg = '&action=create&id=' + $tr.attr('id') + '&path=' + $tr.attr('title');
                    $.ajax({
                        type: 'POST',
                        url: url,
                        data: params + arg,
                        dataType: 'json',
                        success: function (msg) {
                            if (msg.status) {
                                $('#' + msg.id).find('.status').html('<span class="ok">已安装</span>');
                            } else {
                                $('#' + msg.id).find('.status').html('<div class="red">安装失败 <a href="#" onclick="$(this).next().toggle();return false;">[消息]</a><div style="display:none;">' + msg.info + '</div></div>');
                            }
                        },
                        beforeSend: function () {
                            $tr.find('.status').html('<span class="orange">安装中...</span>');
                        }
                    })
                });
            }
        </script>
    </body>
</html>
<?php

// 获取post数据
function query($name) {
    return isset($_POST[$name]) ? $_POST[$name] : '';
}

function create_table() {
    $id = query('id');
    $path = query('path');
    if (!is_file($path)) {
        return array('status' => false, 'id' => $id, 'info' => $path . ' 不存在');
    }
    $sql = file_get_contents($path);
    if (!$sql) {
        return array('status' => false, 'id' => $id, 'info' => $path . ' 无内容');
    }
    $config = array('db_host' => query('db_host'), 'db_name' => query('db_name'), 'db_user' => query('db_user'), 'db_pwd' => query('db_pwd'), 'db_prefix' => query('db_prefix'));
    $link = @mysql_connect($config['db_host'], $config['db_user'], $config['db_pwd']);
    if (false === $link) {
        return array('status' => false, 'id' => $id, 'info' => mysql_error());
    }
    $res = @mysql_query('CREATE DATABASE IF NOT EXISTS ' . $config['db_name'] . ' DEFAULT CHARSET utf8 COLLATE utf8_general_ci;');
    if (false === $res) {
        return array('status' => false, 'id' => $id, 'info' => mysql_error());
    }
    $res = @mysql_select_db($config['db_name']);
    if (false === $res) {
        return array('status' => false, 'id' => $id, 'info' => mysql_error());
    }
    $res = @mysql_query('SET NAMES UTF8');
    if (false === $res) {
        return array('status' => false, 'id' => $id, 'info' => mysql_error());
    }
    $res = @mysql_query($sql);
    if (false === $res) {
        return array('status' => false, 'id' => $id, 'info' => mysql_error());
    }
    $_SESSION['suinstall-db-config'] = $config;
    return array('status' => true, 'id' => $id, 'info' => $id);
}
?>
    